package client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import message.RpcRequestMessage;
import protocol.MessageCodecSharable;
import protocol.ProcotolFrameDecoder;
import protocol.SequenceIdGenerator;
import server.handler.RpcResponseMessageHandler;
import server.service.HelloService;

import java.lang.reflect.Proxy;

@Slf4j
public class RpcClientManager {
  private static Channel channel = null;
  private static final Object LOCK = new Object();

  public static void main(String[] args) {
    HelloService service = getProxyService(HelloService.class);
    System.out.println(service.sayHello("lisi"));
  }

  public static <T> T getProxyService(Class<T> serviceClass) {
    ClassLoader loader = serviceClass.getClassLoader();
    Class[] interfaces = {serviceClass};
    Object o = Proxy.newProxyInstance(loader, interfaces, (proxy, method, args) -> {
      int sequenceId = SequenceIdGenerator.nextId();
      RpcRequestMessage message = new RpcRequestMessage(
              sequenceId,
              serviceClass.getName(),
              method.getName(),
              method.getReturnType(),
              method.getParameterTypes(),
              args
      );
      getChannel().writeAndFlush(message);

      DefaultPromise<Object> promise = new DefaultPromise<>(getChannel().eventLoop());
      RpcResponseMessageHandler.PROMISES.put(sequenceId,promise);
      promise.await();
      if (promise.isSuccess()){
        return promise.getNow();
      }else {
        throw new RuntimeException(promise.cause());
      }
    });
    return (T)o;
  }

  public static Channel getChannel() {
    if (channel != null) {
      return channel;
    }
    synchronized (LOCK) {
      if (channel != null) {
        return channel;
      }
      initChannel();
      return channel;
    }
  }

  public static void initChannel() {
    NioEventLoopGroup group = new NioEventLoopGroup();
    LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
    MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
    // rpc 响应消息处理器，待实现
    RpcResponseMessageHandler RPC_HANDLER = new RpcResponseMessageHandler();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(group);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new ProcotolFrameDecoder());
        ch.pipeline().addLast(LOGGING_HANDLER);
        ch.pipeline().addLast(MESSAGE_CODEC);
        ch.pipeline().addLast(RPC_HANDLER);
      }
    });
    try {
      channel = bootstrap.connect("localhost", 8080).sync().channel();
      channel.closeFuture().addListener((ChannelFutureListener) future -> {
        log.error("client closed");
        group.shutdownGracefully();
      });
    } catch (Exception e) {
      log.error("client error", e);
    }
  }
}
